import cv2
from cvs import *
import numpy as np
import pyzbar.pyzbar as pybar


def 扫码(image):
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    barcodes = pybar.decode(gray)
    print(len(barcodes), barcodes)
    if not barcodes or len(barcodes) < 1:
        x, y = image.shape[0:2]
        text = "Nothing"
        cv2.putText(
            image, text, (x, y // 3), cv2.FONT_HERSHEY_SIMPLEX, 2, (255, 0, 0), 2
        )
        return
    # 这里循环，因为画面中可能有多个二维码
    for barcode in barcodes:
        # 提取条形码的边界框的位置
        (x, y, w, h) = barcode.rect
        cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 5)
        polygonArray = np.array(barcode.polygon)
        print(polygonArray)
        # cv2.drawContours(image, [polygonArray], -1, (0, 0, 255), 2)
        cv2.polylines(image, [polygonArray], True, (0, 0, 255), 2)
        text = f"{barcode.data.decode('utf-8')}"
        cv2.putText(
            image,
            text,
            (x, y + h // 2),
            cv2.FONT_HERSHEY_SIMPLEX,
            1,
            (255, 0, 0),
            2,
        )


def 开启摄像头():
    cap = cvs.VideoCapture(0)

    while True:
        # 读取当前帧
        frame = cap.read()
        if frame is None:
            continue
        扫码(frame)
        cvs.imshow(frame)
        # 按q键退出画面显示


if __name__ == "__main__":
    开启摄像头()
